package com.yixia.framework.web.service;


import com.yixia.system.service.system.SysMenuService;
import com.yixia.system.service.system.SysRoleService;

import com.yixia.common.core.domain.entity.SysRole;
import com.yixia.common.core.domain.entity.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service
public class SysPermissionService {


    @Autowired
    private SysRoleService sysRoleService;
    @Autowired
    private SysMenuService sysMenuService;

    /**
     * 获取角色的数据权限
     */
    public Set<String> getRolePermission(SysUser user){
        /*根据用户id查询角色获取权限*/
        Set<String> roles = new HashSet<String>();
        // 管理员拥有所有权限
        if (user.isAdmin())
        {
            roles.add("admin");
        }else {
            roles.addAll(sysRoleService.selectRolePermissionByUserId(user.getUserId()));
        }
        return roles;
    }

    /**
     * 获取菜单权限集合
     * @param sysUser
     * @return
     */
    public Set<String> getMenuPermission(SysUser sysUser) {
        Set<String> perms = new HashSet<String>();
        // 管理员拥有所有权限
        if (sysUser.isAdmin())
        {
            perms.add("*:*:*");/*超级管理员*/
        }else {
            List<SysRole> roles = sysUser.getRoleList();/*获取所有角色集合*/
            if (!roles.isEmpty() && roles.size() > 1) {
                /*当用户有超过一个的角色时*/
                for (SysRole role : roles) {
                    Set<String> rolePerms = sysMenuService.selectMenuPermsByRoleId(role.getRoleId());
                    role.setPermissions(rolePerms);/*将权限放到角色中去*/
                    perms.addAll(rolePerms);/*收集权限字符*/
                }
            } else if (roles.size() == 1) {
                /*只有一个角色信息*/
                perms.addAll(sysMenuService.selectMenuPermsByUserId(sysUser.getUserId()));
            }
        }
        return perms;
    }
}
